package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Question;
import cn.wolfcode.domain.QuestionItem;
import cn.wolfcode.domain.SaveQuestion;
import cn.wolfcode.mapper.QuestionItemMapper;
import cn.wolfcode.mapper.QuestionMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IQuestionService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class QuestionServiceImpl implements IQuestionService {

    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private QuestionItemMapper questionItemMapper;


    @Override
    public void save(Question question) {
        questionMapper.insert(question);
    }

    @Override
    public void delete(Long id) {
        questionMapper.deleteQuestionItem(id);
        questionMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Question question) {
        questionMapper.updateByPrimaryKey(question);
    }

    @Override
    public Question get(Long id) {
        return questionMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Question> listAll() {
        return questionMapper.selectAll();
    }

    @Override
    public PageInfo<Question> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize()); //对下一句sql进行自动分页
        List<Question> questions = questionMapper.selectForList(qo); //里面不需要自己写limit
        return new PageInfo<Question>(questions);
    }

    @Override
    public List<Question> queryByQuestionList(Long examId, Integer type) {
        return questionMapper.queryByQuestionList(examId, type);
    }

    @Override
    public Workbook exportXls(Integer[] typeArr) {
        Workbook wb = new HSSFWorkbook();
        Sheet sheet = wb.createSheet();
        Row row = sheet.createRow(0);
        row.createCell(0).setCellValue("题目问题");
        row.createCell(1).setCellValue("选项A");
        row.createCell(2).setCellValue("选项B");
        row.createCell(3).setCellValue("选项C");
        row.createCell(4).setCellValue("选项D");
        row.createCell(5).setCellValue("答案");
        List<Question> questionList = questionMapper.queryByQuestionAll(typeArr);
        if(questionList != null){
            for (int i = 0; i < questionList.size(); i++) {
                row = sheet.createRow(i + 1);
                Question question = questionList.get(i);
                row.createCell(0).setCellValue(question.getTitle());
                if(question.getType() == 3){
                    row.createCell(5).setCellValue(question.isJudgeRight() ? "正确" : "错误");
                }else{
                    List<QuestionItem> items = question.getQuestionItems();
                    row.createCell(1).setCellValue(items.get(0).getTitle());
                    row.createCell(2).setCellValue(items.get(1).getTitle());
                    row.createCell(3).setCellValue(items.get(2).getTitle());
                    row.createCell(4).setCellValue(items.get(3).getTitle());
                    row.createCell(5).setCellValue(question.getAns());
                }
            }
        }
        return wb;
    }

    /**
     * 对导入试题文件的解析
     * @param file 导入的文件对象
     */
    @Override
    public void importXls(MultipartFile file) {
        try {
            Workbook wb = new HSSFWorkbook(file.getInputStream());
            Sheet sheetAt1 = wb.getSheetAt(0);
            int lastRowNum1 = sheetAt1.getLastRowNum();
            //获取单选/多选题
            for (int i = 1; i <= lastRowNum1; i++) {
                Row row = sheetAt1.getRow(i);
                String title = row.getCell(0).getStringCellValue();
                if(title == null) return;
                Question question = new Question();
                question.setTitle(title);
                String ans = row.getCell(5).getStringCellValue();
                question.setType(ans.length() > 1 ? 2 : 1);
                questionMapper.insert(question);

                creatQuestionItemList("A." + judgeType(row.getCell(1)), question.getId());
                creatQuestionItemList("B." + judgeType(row.getCell(2)), question.getId());
                creatQuestionItemList("C." + judgeType(row.getCell(3)), question.getId());
                creatQuestionItemList("D." + judgeType(row.getCell(4)), question.getId());
                insertQuestionItem(ans);
                questionItemList.clear();
            }

            //获取判断题
            Sheet sheetAt2 = wb.getSheetAt(1);
            int lastRowNum2 = sheetAt2.getLastRowNum();
            for (int i = 1; i <= lastRowNum2; i++) {
                Row row = sheetAt2.getRow(i);
                String title = row.getCell(0).getStringCellValue();
                if(title == null) return;
                Question question = new Question();
                question.setTitle(title);
                question.setType(3);
                CellType cellType = row.getCell(1).getCellType();
                Integer judge = null;
                if(cellType == CellType.NUMERIC){
                    judge = (int) row.getCell(1).getNumericCellValue();
                }else {
                    judge = Integer.valueOf(row.getCell(1).getStringCellValue());
                }
                question.setJudgeRight(judge == 1);
                questionMapper.insert(question);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取选项集合
     * @param qid 问题id
     * @return 返回选项集合
     */
    @Override
    public List<QuestionItem> queryItem(Long qid) {
        return questionMapper.queryItem(qid);
    }

    /**
     * 单条录入问题
     * @param saveQuestion 问题对象
     */
    @Override
    public void insertQuestion(SaveQuestion saveQuestion) {
        //先清空批量增加题目的选项集合
        questionItemList.clear();
        Question question = new Question();
        question.setTitle(saveQuestion.getQtitle());
        if(!saveQuestion.isChooseType()){
            question.setType(3);
            question.setJudgeRight(saveQuestion.isJans());
        }else {
            question.setType(saveQuestion.getAns().length() > 1 ? 2 : 1);
        }
        questionMapper.insert(question);
        creatQuestionItemList("A." + saveQuestion.getSelOne(), question.getId());
        creatQuestionItemList("B." + saveQuestion.getSelTwo(), question.getId());
        creatQuestionItemList("C." + saveQuestion.getSelThree(), question.getId());
        creatQuestionItemList("D." + saveQuestion.getSelFour(), question.getId());
        insertQuestionItem(saveQuestion.getAns());
    }

    @Override
    public void updateQuestion(SaveQuestion saveQuestion) {
        questionMapper.deleteQuestionItem(saveQuestion.getQid());
        if(saveQuestion.getQtype() == 3){
            questionMapper.updateQuestion(saveQuestion);
        }else{
            creatQuestionItemList(saveQuestion.getSelOne(), saveQuestion.getQid());
            creatQuestionItemList(saveQuestion.getSelTwo(), saveQuestion.getQid());
            creatQuestionItemList(saveQuestion.getSelThree(), saveQuestion.getQid());
            creatQuestionItemList(saveQuestion.getSelFour(), saveQuestion.getQid());
            insertQuestionItem(saveQuestion.getAns());
        }
    }

    /**
     * 判断单元格值的类型
     * @param cell 单元格
     * @return 返回单元格值的字符串
     */
    private String judgeType(Cell cell) {
        CellType cellType = cell.getCellType();
        String str = null;
        if(cellType == CellType.NUMERIC){
            str = Integer.valueOf((int) cell.getNumericCellValue()).toString();
        }else{
            str = cell.getStringCellValue();
        }
        return str;
    }

    /**
     * 存储选项的中间集合,每次插入一条问题记录都会清空
     */
    private static List<QuestionItem> questionItemList = new ArrayList<>();

    /**
     * 将选项对象存入questionItemList选项集合中
     * @param title 选项标题
     * @param questionId 问题ID
     */
    private void creatQuestionItemList(String title, Long questionId) {
        QuestionItem questionItem = new QuestionItem();
        questionItem.setTitle(title);
        questionItem.setQuestionId(questionId);
        questionItemList.add(questionItem);
    }

    /**
     * 遍历插入选项记录
     * @param ans 问题的答案
     */
    private void insertQuestionItem(String ans) {
        List<Integer> set = new ArrayList<>();
        if(!StringUtils.isEmpty(ans)){
            char[] chars = ans.toCharArray();
            for (char aChar : chars) {
                set.add(aChar - 'A');
            }
        }
        if(questionItemList != null){
            for (int i = 0; i < questionItemList.size(); i++) {
                if(set.contains(i)){
                    questionItemList.get(i).setJudgeRight(true);
                }
                questionItemMapper.insert(questionItemList.get(i));
            }
        }
    }

}
